package com.example.shengyin.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class ImageCompressor {

    public static String yasuo(String path,String imgpath, String houzhui) {
        File input = new File(path+"/"+imgpath);
        String imgname=UUID.randomUUID() +"."+ houzhui;
        File output = new File(path+"/"+imgname);
        System.out.println(path+"/"+imgpath);
        System.out.println(path+"/"+imgname);

        try {
            BufferedImage originalImage = ImageIO.read(input);
            int scaledWidth = originalImage.getWidth();
            int scaledHeight = originalImage.getHeight();

            // 计算压缩比例，以保持图片质量并压缩到指定大小以下
            double compressionRatio = 1.0;
            while (scaledWidth * scaledHeight * compressionRatio > 5000) {
                compressionRatio -= 0.1;
            }


            BufferedImage resizedImage = new BufferedImage(
                    scaledWidth,
                    scaledHeight,
                    BufferedImage.TYPE_INT_RGB);


            resizedImage.getGraphics().drawImage(
                    originalImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH),
                    0,
                    0,
                    null);


            // 输出压缩后的图片
            ImageIO.write(resizedImage, houzhui, output);
            return imgname;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
